I have a textbox.The user will be entering entering a number in this box.The user should enter two digits followed by a period "." and another digit.It would look something like 22.3 or 00.5 or 01.2.
If the textbox is not empty,I want to enforce a function which validates the value entered by the user(and gives them an alert if the value entered is not according to the format mentioned above) .This function needs to be triggered when the textbox loses its focus.I am not sure how to go ahead in writing this function as i am still new to this. Any help would be appreciated.Thanks in advance.
p.s This function should be triggered e开发者_Go百科ach time there is a change in the value.Like suppose, the user enters a value 22, then when the textbox loses its focus,the javascript function should be triggered giving them an alert asking the user to change it to the accepted format which is 22.0.The function should be triggered again when the textbox loses its focus(after the change has been done).This time there would not be an alert since the user entered it in the right format.
Excuse the Prototype specific code, but maybe you'll get the gist of it. You'll want to listen on the "onblur" event of the textarea, and then validate the entered value with a regular expression.
Event.observe('textboxId', blur, function() {
var val = $F('textboxId');
if (/^\d{2}\.\d$/.test(val)) {
alert('Invalid value');
}
});
If you're not familiar with any javascript frameworks, and just want to get this working, try this:
<textarea onblur="validate(this.value);"></textarea>
<script type="text/javascript">
function validate(val) {
if (/^\d{2}\.\d$/.test(val)) {
alert('Invalid value');
}
}
</script>
Purists, please don't punish me for adding this.
精彩评论