jQuery matching pattern
I'm trying to validate my inputs with jQuery before a form is sent.
This is what my input fields look like when there is no value inserted in the database:
<input
class="field"
type="text"
style="background-color: rgb(255, 255, 255);"
value="" name="input_18748_388_1257894000_"/>
This is what my input fields look like when there is an existing value inserted in the database:
<input
class="field"
type="text"
style="background-color: rgb(255, 255, 255);"
value=""
name="input_18748_388_1257894000_46549876"/>
I would like to:
Check if the value is already in the database
Check开发者_StackOverflow中文版 if the user want to replace an existing value by nothing or zero and disallow it.
Check if the user is trying to insert 0 in a new field and disallow it.
Solved:
$("input[name^='input_"+var+"_']")
.each(function() {
if ($(this).attr('name').match(/^input_\d+_\d+_\d+_\d+/)
&& ($(this).val() == '' || $(this).val() <= 0))
{
displayDialog("<?=_('error')?>")
flag_error = 1;
return false;
}
});
// Submit the form.
Try this:
$('input[name]')
.filter (function () {
return $(this).attr('name').match (/^input_\d+_\d+_\d+_.+/$);
})
.each (function () {
if ($(this).val() <= 0) {
//... raise a fuss ...
}
});
This needs to be called on submit
or change
as you prefer.
You need to bind a keydown event and check keycodes. This example will disable space and the 0 char in input fields with the name attribute ending with '_':
$('input[name$=_]').bind('keydown', function(e) {
var key = e.keyCode || e.which;
if (key == 48 || key == 32) {
e.preventDefault();
}
})
$("input[name^='input_"+var+"_']")
.each(function() {
if ($(this).attr('name').match(/^input_\d+_\d+_\d+_\d+/)
&& ($(this).val() == '' || $(this).val() <= 0))
{
displayDialog("<?=_('error')?>")
flag_error = 1;
return false;
}
});
You may benefit the Regex Selector for jQuery Plugin. It allows code like:
$('div:regex(input,^input_(\d+|)+_?$)'); //just an example regex
Also, note that you can combine multiple attribute selectors, ie:
$("input[name^='input_'][name$='_']")
Add a class "my_very_special_input" to every input element you would like to validate that way:
$(".my_very_special_input").change( function() {
if ($(this).val() <= 0) {
alert('You cant delete this');
flag_error = 1;
return false;
}
});
精彩评论