I tried to write a regular expression to work with the position-absolute jQuery validation plugin to give error if the string is left empty OR its a invalid URL. It works well for the URl but doesn't give error if a empty string is there . Here's the regex
"regex": /^\S$|^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/,
Can somebody tell what's wrong in the regex?
EDIT:
I'm using this plugin for jQuery validation
Demo: Go to this URL and in the URL validtion section, remove HTTP and see the error messages
http://www.position-relative.net/creation/formValidator/demos/demoValidators.html
When I add required and URL validators together, it shoots 2 errors. But with only URL
validator, it doesn't say that its a Invalid URL. I just need 1 error for both Empty and
Invalid URL.
https://github.com/posabsolute/jQuery-Validation-Engine
Thanks
You can set the same generic error message for all errors using data-errormessage, so regardless of whether the field is empty or has an invalid value you will get the same message.
have you tried jQuery URL validation metohod ?
I wrote a small example how you could validate a email realy quick and easy. Without the hassle of using a plugin. If you use it just once you could just use
var emailaddressVal = 'nobody#example.cpom';
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(emailReg.test(emailaddressVal) && emailaddressVal.length > 0)
{
alert('Your email is valid.');
}
else
{
alert('The email is invalid')
}
However putting it in a function so you could use it multiple times. than put it in a function for example:
// Email check function
function checkEmail(email)
{
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(emailReg.test(email) && email.length > 0)
{
return true;
}
else
{
return false;
}
}
// Ussage
if(checkEmail('nobody#example.com'))
{
alert('SUCCESS!!');
}
else
{
alert('FAILED!!');
}
Related
Javascript isn't really my strong point. I already have the php working for the captcha on the backend but i want to be able to validate the form with JS to prevent the user from sending a form when the captcha hasn't been completed.
This is the example the hcaptca site gives:
https://medium.com/#hCaptcha/using-hcaptcha-with-php-fc31884aa9ea
And here is the JS code they give as an example.
$("form").submit(function(event) {
var hcaptchaVal = $('[name=h-captcha-response]').value;
if (hcaptchaVal === "") {
event.preventDefault();
alert("Please complete the hCaptcha");
}
});
I'm not 100% sure but that appears to be Jquery and my site does not use Jquery. so i need a vanilla JS solution.
Let me try to explain:
$("form").submit(function(event) { }
// When the form is submitted
var hcaptchaVal = $('[name=h-captcha-response]').value;
// Retrieve the value of the captcha (= the value of an HTML element with the tag name="h-captcha-response"
if (hcaptchaVal === "") {
event.preventDefault();
alert("Please complete the Captcha");
}
// If the value of the captcha is empty, stop the form submission and alert the user
So if you are searching for a Vanilla JS solution, it's not that hard, all you have to do is convert the jQuery parts :
document.querySelector("#yourFormId").addEventListener("submit", function(event) {
var hcaptchaVal = document.querySelector('[name="h-captcha-response"]').value;
if (hcaptchaVal === "") {
event.preventDefault();
alert("Please complete the hCaptcha");
}
});
i am developing application using Code-igniter.
I want to validate Text Box Using J Query Or JavaScript That only allowed to input following URL when user submit form.
http://
https://
ftp://
ftps://
file://
market://
linkedin://
fb://
geo:
maps://
Is there any way to do this ?
function is_url(str)
{
regexp = /^(?:(?:https?|ftps?|file?|market?|linkedin?|fb?|maps?):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;
if (regexp.test(str))
{
return true;
}
else
{
return false;
}
}
Try using this regex in a function that checks validity of your input.
/^(http|https|ftp|ftps|file|market|linkedin|fb|maps|geo):\/\//g
But do the reverse logic:
if it matches then display error mesage and clear input.
If it not matches then your URL is fine
If you wanna prevent URLs anywhere in your input, remove the leading ^ in regex to match even if URL is not start of the string.
like: /(http|https|ftp|ftps|file|market|linkedin|fb|maps|geo):\/\//gm
Here is a crud version of entire solution:
fiddlejs
Main thing is URL validation:
$("#urlInput").focusout(function (){
var inputElement = $("#urlInput");
var regexp = /(http|https|ftp|ftps|file|market|linkedin|fb|maps|geo):\/\//gm;
if (regexp.test(inputElement.val())){
inputElement.val("");
alert("This is nto a valid URL")
}
});
It bound to the
<input id="urlInput" type="url">
You might wanna rework the error reporting in a more user friendly manner but that's another story.
I wrote the code for form field validation in JavaScript,
but it's not working properly as my requirement.
URLs only support:
http
https://
and (www.xyz.com , xyz.com ,xyz.co.in )
My code :
var file_url = document.getElementById(url);
if(file_url.value.match(^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$)){
alert('Please Enter valid Url');
return false;
}
but it does not work as expected
^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$
Try this.See demo.
https://regex101.com/r/tX2bH4/58
After many trails i got this one better,I have tried this one working perfectly.I think this one also correct one.
if(!file_url.value.match(/(^|\s)((https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)/gi)){
alert('Please Enter valid Url');
return false;
}
Here is the demo: Demo of regex
Sorry for this most likely simple question.
I am running a script on submission of the form (code below), but first I would like to validate the form (contains one text box which must be an email) before the code is executed.
The script below is taken from here to ensure the form data is passed along to the colorbox lightbox script. But i only want to run this if the form is validated. I don't know how to combine this with an email validation script. Help! At the moment i've got a script that validates email (dreamweaver's) and this running, this command still runs even if it doesn't validate and i am not sure how to edit it so it doesn't.
$(document).ready(function() {
$("input#SearchButton").colorbox({href: function(){
var url = $(this).parents('form').attr('action');
var ser = $(this).parents('form').serialize(); //alert(url+'?'+ser);
return url+'?'+ser;
}, innerWidth:"1280", innerHeight:"884px", iframe:true, scrolling:false});
});
Then I am using this to validate the form:
function MM_validateForm() { //v4.0
if (document.getElementById){
var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
if (val) { nm=val.name; if ((val=val.value)!="") {
if (test.indexOf('isEmail')!=-1) { p=val.indexOf('#');
if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
} else if (test!='R') { num = parseFloat(val);
if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
min=test.substring(8,p); max=test.substring(p+1);
if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
} }} else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
} if (errors) alert('The following error(s) occurred:\n'+errors);
document.MM_returnValue = (errors == '');
} }
Thanks!!!!
The HTML for the tigger is:
<input name="submit" type="image" onclick="MM_validateForm('email','','RisEmail');return document.MM_returnValue" src="images/go-button.gif" alt="Go! Get quote now!" align="top" : id="SearchButton"/>
In a nutshell: I want to tigger the code in the first snippet if the form validates using the code in the second snippet that is called by the html even in the third code snippet, but not if it doesn't.
You didn't post your HTML so I don't know if you have an actual form or just an input field without an actual form tag.
Assuming the former, you need a submit event so you can validate the form and then, if validation failed, terminate the submission.
$('#my_form').submit(function() {
//validate - forget the whole thing if it fails
if (!$('#my_field').val()) return false;
//if we get this far, validation succeeded - do other stuff now
});
A form submission is halted any time the submit callback returns false (or fires event.preventDefault()).
Andrew is correct, it would help if you provided the html in order to establish what the event trigger will be. Having reviewed the jquery plugin 'colorbox' briefly, it appears the lightbox is bound to the selectors click event.
Assuming Andrew's answer, if the email address validates you would need to manually trigger the click event for the lightbox from within the submit handler for the form. The following code should suffice.
$('#my_form').on('submit', function(e){
//perform validation.
MM_validateForm('email','','RisEmail');
//check the document variable set by the validation.
if (!document.MM_returnValue)
{
//did not validate
}else{
//open the colorbox
var search_btn = $('input#search');
search_btn.colorbox({href: function(){
var url = $(this).parents('form').attr('action');
var ser = $(this).parents('form').serialize();
return url + '?' + ser;
},
innerWidth: "1280",
innerHeight: "884px",
iframe:true,
scrolling:false});
//manually trigger the click event
search_btn.trigger('click');
}
//in either instance, disable the default action to ensure the form does not follow through.
e.preventDefault();
});
Obviously you'll have to replace the css selector names with your own, and utilise the email validation script that you may or may not have.
I have an html file which contains a form. There is lots of text typed input control need customer to input information. How do I check whether the customer's input is correct?
For example, I want to check if the username only contains digits, letters and '_'.
Please help me.
I'd appreciate if somebody can provide me a demo.
Thanks in advance!
Here’s one possible approach, for a simple task like the one given as example:
<script>
function check(elem) {
if(elem.value.match('^' + elem.getAttribute('pattern') + '$')) {
return true;
} else {
alert(elem.getAttribute('data-msg'));
return false;
}
}
</script>
<input name=username pattern=[a-zA-z0-9_]{1,9} onblur=check(this)
data-msg="The user name may only contain letters A–Z, digits, and underlines and must be 1 to 9 characters.">
The idea here is to start with the HTML5 pattern attribute, specifying the allowed pattern of data as a regular expression. It already works on several modern browsers and does no harm when it doesn’t. Then you add an event attribute, which causes a JavaScript-driven check to be made, using the regular expression taken from the same attribute (with a prefix and postfix character added so that the check is made on the input item as a whole).
You may wish to display the error message in some less disruptive manner than via alert()
<input type="text" id="username" />
<span id="invalidMessage" style="display:none; color:Red"><img src="../../Images/error.gif" alt="OK" />invalidEmail。</span>
<script type="text/javascript">
$(document).ready(function() {
$('#username').blur(function() {
$('#invalidMessage').hide();
if ($('#username').val() != "") {
var email = /_*\w+(-?\w+)*#_*\w+(-?\w+)*(._*\w+(-?\w+)*)*.\w*/;
if (!email.test($('#username').val())) {
$('#invalidMessage').show();
}
}
});
});
</script>
There is a demo,hope can help you.
I would use something like this on the client side;
<script type="text/javascript">
<!--
function validate_form ( )
{
valid = true;
if ( document.contact_form.contact_name.value == "" )
{
alert ( "Please fill in the 'Your Name' box." );
valid = false;
}
return valid;
}
//-->
</script>
Then, i would use more robust error checking on the server side to ensure you have valid data. If you can catch bad data at the client, its a plus, as it avoids the hit on the server, but the validation really belongs on the data on the server side, as its more secure and can be reused by other forms.