gpt4 book ai didi

javascript - 进行验证时的 jQuery 问题

转载 作者:行者123 更新时间:2023-11-28 08:36:44 25 4
gpt4 key购买 nike

我正在尝试使用 jQuery 验证文件进行表单验证。这让我很难受...这是一个简单的表单,我现在要做的是检查用户名输入:

  • 不能以数字开头
  • 不能只是数字
  • 不能以符号开头
  • 不能只是符号
  • 应类似于此示例:用户名 = panchi15_ 或 jack 或 a77

这是 html 片段:

  <div class="row-fluid">
<div class="span6 ">
<div class="control-group">
<label class="control-label">Usuario<span class="required">*</span></label>
<div class="controls">
<input type="text" name="username" value="" class="m-wrap span8" required/>
</div>
</div>
</div>

在此文件的顶部,我调用以下文件:

<script type="text/javascript" src="{site_url()}assets/plugins/jquery-validation/dist/jquery.validate.min.js"></script>
<script type="text/javascript" src="{site_url()}assets/plugins/jquery-validation/dist/additional-methods.js"></script>

我的js文件:

var FormValidation = function () {

var handleValidation2 = function() {
// for more info visit the official plugin documentation:
// http://docs.jquery.com/Plugins/Validation

var form2 = $('#form-val');
var error2 = $('.alert-error', form2);
var success2 = $('.alert-success', form2);

//IMPORTANT: update CKEDITOR textarea with actual content before submit
form2.on('submit', function() {
for(var instanceName in CKEDITOR.instances) {
CKEDITOR.instances[instanceName].updateElement();
}
})

form2.validate({
errorElement: 'span', //default input error message container
errorClass: 'help-inline', // default input error message class
focusInvalid: false, // do not focus the last invalid input
ignore: "",
rules: {
//utilizo el plugin additional-methods.js para crear algunas reglas y validar
username: {
minlength: 2,
maxlength: 15,
// pattern: "[a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*",
//el nombre de usuario no puede empezar con numeros
// pattern: "/^!=.*\d\w{2,15}$/",
pattern: true,
required: true

},

name: {
minlength: 2,
maxlength: 50,
// regex: ,
required: true
},

lastname: {
minlength: 2,
maxlength: 50,
required: true
},

gender: {
required: true
},

date_born: {
required: true
},

email: {
required: true,
email: true
},

status: {
required: true
},

member_id: {
minlength: 5,
},

documentType_id: {
required: true
},

documentn: {
required: true,
minlength: 2
},
address_street: {
required: true
},

address_number: {
required: true
},

address_floor: {
required: false
},

zipcode: {
required: true
},

city: {
required: true
},

state: {
required: true
},

country_id: {
required: true
},

phone: {
required: true
},

cellphoneNumber: {
required: true
},

cellCompany: {
required: true
},

cellbrand: {
required: true
},

marital_status: {
required: true
},

sons: {
required: true
},
},

messages: { // custom messages for radio buttons and checkboxes
username: {
// required: "Este campo es requerido",
minlength: "Mínimo 2 caracteres",
maxlength: "Máximo 15 caracteres",
// remote: "No Disponible"

},

membership: {
required: "Please select a Membership type"
},
service: {
required: "Please select at least 2 types of Service",
minlength: jQuery.format("Please select at least {0} types of Service")
}
},

// errorPlacement: function (error, element) { // render error placement for each input type
// if (element.attr("name") == "education") { // for chosen elements, need to insert the error after the chosen container
// error.insertAfter("#form_2_education_chzn");
// } else if (element.attr("name") == "membership") { // for uniform radio buttons, insert the after the given container
// error.addClass("no-left-padding").insertAfter("#form_2_membership_error");
// } else if (element.attr("name") == "editor1" || element.attr("name") == "editor2") { // for wysiwyg editors
// error.insertAfter($(element.attr('data-error-container')));
// } else if (element.attr("name") == "service") { // for uniform checkboxes, insert the after the given container
// error.addClass("no-left-padding").insertAfter("#form_2_service_error");
// } else {
// error.insertAfter(element); // for other inputs, just perform default behavior
// }
// },

invalidHandler: function (event, validator) { //display error alert on form submit
success2.hide();
error2.show();
App.scrollTo(error2, -200);
},

highlight: function (element) { // hightlight error inputs
$(element)
.closest('.help-inline').removeClass('ok'); // display OK icon
$(element)
.closest('.control-group').removeClass('success').addClass('error'); // set error class to the control group
},

unhighlight: function (element) { // revert the change done by hightlight
$(element)
.closest('.control-group').removeClass('error'); // set error class to the control group
},

success: function (label) {
if (label.attr("for") == "service" || label.attr("for") == "membership") { // for checkboxes and radio buttons, no need to show OK icon
label
.closest('.control-group').removeClass('error').addClass('success');
label.remove(); // remove error label here
} else { // display success icon for other inputs
label
.addClass('valid').addClass('help-inline ok') // mark the current input as valid and display OK icon
.closest('.control-group').removeClass('error').addClass('success'); // set success class to the control group
}
},

submitHandler: function (form) {
success2.show();
error2.hide();
}

});

// $('#form-val').select2({
// placeholder: "Select an Option",
// allowClear: true
// });

// //apply validation on chosen dropdown value change, this only needed for chosen dropdown integration.
// $('.chosen, .chosen-with-diselect', form2).change(function () {
// form2.validate().element($(this)); //revalidate the chosen dropdown value and show error or success message for the input
// });

// //apply validation on select2 dropdown value change, this only needed for chosen dropdown integration.
// $('.select2', form2).change(function () {
// form2.validate().element($(this)); //revalidate the chosen dropdown value and show error or success message for the input
// });
}

return {
// main function to initiate the module
init: function () {
handleValidation2();
}
};
}();

如果用户输入有效的用户名,则输入旁边应出现一个绿色的“确定”图标。否则,输入框应为红色,并带有图例,说明错误所在。

我做错了什么?

更新: http://jsfiddle.net/jimena/wXm3p/

最佳答案

我会回答我的问题,以防将来其他人需要它。我可以找出我做错了什么。

在 jQuery 验证文件之一additional-methods.js 中,有一个与单词模式相关的函数:

jQuery.validator.addMethod("pattern", function(value, element, param) {
if (this.optional(element)) {
return true;
}
if (typeof param === 'string') {
param = new RegExp('^(?:' + param + ')$');
}
return param.test(value);
}, "Invalid format.");

如您所见,它接收 3 个参数:值、元素和参数。 Param 是您定义的正则表达式,用于匹配代码行中已有的预定义元素:

param = new RegExp('^(?:' + param + ')$');

在我创建的js文件中,您可以在我的问题中看到,仅使用了这个:

   pattern: "[A-z](([\._\-][A-z0-9])|[A-z0-9])*[a-z0-9_]*"

就是这样。

关于javascript - 进行验证时的 jQuery 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21048591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com