Reputation: 1211
I need to validate my textbox using JavaScript, so far i made this :
$(document).ready(function(){
$('#search_form').validate({
rules: {
searchText:{
required: true,
number: true
},
},
messages: {
searchText: {
required: "required",
number: "must be a number"
}}
})}
);
it works fine but i also need to show a message if user presses the search button without enter any value, and of course the textbox is containing the message "please enter your number" (using placeholder).
the serach form :
<form method="get" id="search_form">
<input type="button" value="search" id="search" />
<input type="text" name="searchText" id="searchText" placeholder="please enter your number" />
</form>
the current code doesn't show anything if user presses search button without inserting a number, but if he inserts letters for example he will get the message "must be number" and if he deletes any value was there in textbox, he will get the message "required".
i tried :
searchText:{
required: { depends: function()
{ return $( "#searchText" ).val() == 'please enter your number '} },
number: true
},
but nothing changes.
i hope i could explain my question good.
Thanks!
you are right it works fine if i delete whatever value in the textbox i get required msg. but since i made the validation on the form, it didn't response on the button clocking. how i can add a validation on the button too ?
Upvotes: 0
Views: 1251
Reputation: 359
Remember that your string comparison is an exact search. It looks like you have an extra space in the code you tried, after the word "number." Try removing that space and testing again. If the value of the textfield exactly matches the placeholder value, then your depends
method should return true. Alternatively, you could try $.trim()
to ensure that whitespace from the beginning and end of the string is removed.
Another approach you may consider would be to instantiate a "original value" property (using jQuery's data
methods) so that if your placeholder value were to change, you wouldn't need to update your JavaScript validation code.
Upvotes: 0