Yes, I know that data sanitation and validation must be done server-side, but please stay with me.
Using the following script, stackoverflow.com
will fail validation since a protocol is not given. If a URL is inputted without a protocol, I wish to add a default protocol (http://) to the input value prior to client-side validation. I don't wish to relax the validation method to silently accept URLs without a protocol as the user should be aware that a protocol was added.
How is this best accomplished?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Testing</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
var validator=$("#myForm").validate({
rules: {
url: {url:true,}
},
});
//Added per Monax's suggestion.
$('#url').blur(function(){this.value=this.value.substring(0,4)=='http'?this.value:(this.value?'http://'+this.value:'');});;
});
</script>
</head>
<body>
<form id="myForm" method="post">
<input name="url" id="url" value="">
<input type="submit" />
</form>
<?php echo('<pre>'.print_r($_POST,1).'</pre>');?>
</body>
</html>
You don't want to write a custom rule and you insist on manipulating the data before validation. Your options are limited since the plugin is automatically capturing all the validation triggering events. This is my suggested workaround.
Create two input fields...
Upon entering any data into visible field, you would programmatically copy and modify the data as needed into the hidden field.
Then programmatically trigger validation on the hidden field.
Something like this.
HTML:
jQuery:
NOTES:
You'll have to enable validation on hidden fields by properly setting the
ignore
option to something that allows it.[]
will enable validation on all hidden fields.You might have to use the
errorPlacement
option to tweak the placement of the error message for this hidden field. You can do this conditionally.