URL validation in text input - javascript

How do I validate the url in a text input if the user accidentally write on the text input before clicking submit?

Try below code, this will work for you
function urlLocate() {
var url = document.getElementById("url").value;
var regexp = /^(?:(?:https?|ftp):\/\/)?(?:(?!(?: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 (url != "") {
if (!regexp.test(url)) {
alert("Please enter valid url.");
} else {
window.location.assign(url);
}
}
else {
alert("Please upload an image.");
}
}

try this function for Url validation.
function isUrlValid(userInput) {
var res = userInput.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*)/g);
if(res == null)
return false;
else
return true;

try this function for validating url
function ValidURL(str) {
var pattern = new RegExp('^(https?:\/\/)?'+ // protocol
'((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|'+ // domain name
'((\d{1,3}\.){3}\d{1,3}))'+ // OR ip (v4) address
'(\:\d+)?(\/[-a-z\d%_.~+]*)*'+ // port and path
'(\?[;&a-z\d%_.~+=-]*)?'+ // query string
'(\#[-a-z\d_]*)?$','i'); // fragment locater
if(!pattern.test(str)) {
alert("Please enter a valid URL.");
return false;
} else {
return true;
}
}

Use form and <input type="url"> to validate it. The form can only be submitted with the valid value(s).
$('form').on('submit', function(e){
e.preventDefault();
console.log('valid URL');
});
<form>
Input a URL: <input type="url" required><br>
<input type="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I agree with #NoobTW and #Azer to use <input type="url"
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/url
Examples without any JS:
Demand a URL prefix but you can make one up yourself. Both http:// and bonk:// will be accepted as valid url prefixes.
<form>
<input type="url" required />
<input type="submit" value="Submit Now!">
</form>
URL validation by demanding that all url's start with either http:// or https://
<form>
<input type="url" pattern="https?://.+" required />
<input type="submit" value="Submit Now!">
</form>
Require https:
<form>
<input type="url" pattern="https://.+" required />
<input type="submit" value="Submit Now!">
</form>
https://html5-tutorial.net/form-validation/validating-urls/
With simple error message:
<form>
<input type="url" pattern="https://.+" required title="Requires https://" />
<input type="submit" value="Submit Now!">
</form>
If you wish to replace Default HTML5 Validation Message you can do it like this:
https://webdesign.tutsplus.com/tutorials/html5-form-validation-with-the-pattern-attribute--cms-25145#Replacing%20the%20Default%20HTML5%20Validation%20Message

type="url"
You can give the input type="url" to give it a simple validation as mentioned above.
<input type="url" required>
Please note that you should also give it the required attribute if a valid URL is required to submit the form.
pattern attribute
You can also give the input the pattern attribute if you want to add your own custom validation. The pattern attribute takes a regex pattern as it's value and will match it to the value of the input at validation. If you use a pattern attribute to do your own custom validation, you don't need to use the "url" input type. A simple text input will work as well.
<input type="text" pattern=".*\.[a-z]{2,}$" required>
The above is an overly simplified regex pattern that will only recognize very plain urls (like example.com) and should not be used for any serious validation. But you can change the pattern to any one of the patterns used in functions suggested in other answers, or some other pattern that fit your needs.
Both combined
<input type="url" pattern="https?:\/\/*" required>
The above is a simple example of a url input where a pattern attribute has been applied to make the validation a little bit stricter. This way the value of the input has to pass both the standard validation of a url input field, but it also has to pass the regex pattern to be validated. In the above example, the url has to begin with either http:// or https:// to pass validation.

Related

Set focus to another field in web form with javascript

I have a web form with two fields:
Email
User name
I want to track user input in the Email field and when it ends with ".com" set focus to another field "User email"
What the best way to do so with JavaScript or jQuery.
This should do the trick. When the last 4 letters of the email input are '.com', the focus is given to the username field.
While this works, please consider the UX issues this may cause. In the comments for your question, Quentin provides a good explanation of why this probably isn't worth implementing.
$('#email').on('input', function() {
email = this.value
if (email.substr(email.length - 4) === '.com')
$('#username').focus()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="email" type="text" placeholder="email">
<input id="username" type="text" placeholder="user name">
as #Quentin mentioned this not a best practice due to these types of emails such as (.com.au)
but if you really know what you are doing then this code does what you want
// select email input
const mail = document.getElementById('mail');
// add input event
mail.addEventListener('input', e => {
// get value
let value = e.target.value.trim();
const regex = /.com$/ig; // matches any string ends with .com
const result = regex.test(value);
// if matches .com at the end then add focus to name input
if (result) {
e.target.nextElementSibling.focus();
}
});
<form>
<input type="text" placeholder="insert your email" id="mail">
<input type="text" placeholder="insert your name" id="name">
</form>

Check value from a string after a special character if it's not empty

im working in little projet, and i have a little issue
So first im working in a form with differents inputs
the first input called by ID is #name
I try to write a code to check if my user fill the input correctly with this tructure
fisrtname_lastname
what i try to do on my sence, is to check first if the user type ( _ ) in the input, and check if he continue to add more infos after the special character.
and the others steps is when he fill in the right way the submit button is actif
$('#submit').removeAttr('disabled');
if its not its gona be inactif
$('#submit').attr('disabled', 'disabled');
** input code**
<input type="text" class="form-control text" name="p_Nom" id="name" maxlength="24" placeholder="firstname_Prenom" />
** Jquery part **
$('#name').keyup(function() {
$('#submit').attr('disabled');
let val = $(this).val();
if( (val.includes('_')) && (val.substr(val.indexOf('_') + 1) == null) ){
$('#submit').removeAttr('disabled');
} else{
$('#submit').attr('disabled', 'disabled');
}
});
You might consider using a regex instead: use the pattern [A-Za-z]+_[A-Za-z]+ for the input. No jQuery necessary:
<form>
<input pattern="[A-Za-z]+_[A-Za-z]+">
<button>Submit</button>
</form>
Or, to permit other non-alphabetical characters, use a negative character set instead:
<form>
<input pattern="[^_]+_[^_]+">
<button>Submit</button>
</form>
If you also need to run Javascript when invalid, add an invalid event listener:
$('input').on('invalid', () => {
console.log('invalid');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input pattern="[^_]+_[^_]+">
<button>Submit</button>
</form>

Don't process the <form> if the <input> DOESN'T contain an underscore

Form:
<form action="goto.php" method="post" name="myform" id="myform" onsubmit="return formSubmit(this);" class="form-wrapper cf">
<input name="statusid" autocomplete="off" id="statusid" placeholder="Enter ID Here" type="text">
<input name="submit_btn" class="submit" id="submit_btn" value="" placeholder="submit" >
</form>
Demo - http://jsfiddle.net/FEF7D/4/
Some users submit an ID that has only numbers in it (e.g. 981734844).
And some users submit an ID that has underscore "_" (without quotes) in it (e.g. 28371366_243322).
What I want to do is NOT allowing the users that submit an ID with ONLY numbers in it (e.g. 89172318) to process the form action.
In other words:
82174363278423: Don't allow to process the form action
21489724893249_2918423: Allow to process the form action
Is it possible to do that?
Thanks in advance.
Try this...
function formSubmit(form) {
// create a regex to test for the numbers + underscore + numbers pattern
var rx = /^\d+_\d+$/,
test = rx.test(form.statusid.value);
test || alert('You need to enter an ID with underscore in it.');
return test;
}
Demo - http://jsfiddle.net/FEF7D/7/
you need to use java script validation and in that you can use following code:
if ( String.indexOf('_') != -1 ) {
// your form processing code..
}
Yes you can do that. There are a number of solutions. For example, you can split your input string into an array using the underscore as the split divider and if your array has two entries, you know you've got a single underscore. e.g. Something like this (untested snippet to illustrate - you also need to add numeric checks for each part of the array so you probably want to assign the split to a variable if going with this approach):
$('form').submit(function(event)
{
if (myinputvar.split('_').length ! = 2)
{
event.preventDefault();
return false;
}
// do the rest of your submission here
});
You can do any form validation in onsubmit of form.
HTML
<form name="myform" id="myform" onsubmit="return formSubmit(this);" class="form-wrapper cf" action="goto.php" method="post">
<input name="statusid" autocomplete="off" id="statusid" placeholder="Enter ID Here" type="text">
<input type="submit" name="submit_btn" class="submit" id="submit_btn" value="" placeholder="submit" >
</form>
JavaScript
// Do validation of form
function formSubmit(formObj) {
// Only allowable character is numeric or underscore
if (!/^[_0-9]*$/.test(formObj.statusid.value)) {
return false;
}
return true;
}
The two answers above will work (just strip out Neil's jquery).
Another option is
function formSubmit(form){
var statusid=document.getElementById("statusid");
if(statusid.value.search("_")===-1){
alert('ID must have an underscore "_".');
}
};
unfortunately, for some reason I can't get that to work with jsfiddle, it's telling me formSubmit is not a function, but clearly it is. Either way, javascript has a 'search' method on strings.

jQuery validation engine, set minsize but allow empty

I have using jQuery validation engine,
I try to let empty text field, but validate while the field not empty
my code is like this
<input name="t_city" type="text" id="t_city" placeholder="CITY" class="validate[minSize[6]]">
and my javascript is like this
$("form").validationEngine({
onValidationComplete:function(form, status){
var city = $("input#t_city").val();
if(status == true){ alert(city); }
}
}
}
How to validate to allow if the input field is empty.?
change class="validate[minSize[6]]" to class="validate[optional,minSize[6]]"
HTML:
<input name="t_city" type="text" id="t_city" placeholder="CITY" class="validate[optional,minSize[6]]">

How to use onClick ONLY if email input field is valid?

Here's code:
<input id="subscribe-email" type="email" placeholder="john.doe#example.com" />
<button type="submit" id="subscribe-submit" onClick="javascript:omgemailgone();" />
How do I check and run JS function only if email is valid (validation by user-agent, no additional validations)?
UPDATE.
New browsers can validate input=email by themselves, also there are pseudo classes :valid and :invalid. I need to run function only if browser 'knows' that email is valid.
You can use the .checkValidity() method of the input element (in this case, the email input field). This will return a boolean indicating wether the input is valid or not.
Here is a fiddle to play with:
http://jsfiddle.net/QP4Rc/4/
And the code:
<input id="subscribe-email" type="email" required="required" placeholder="john.doe#example.com" />
<button type="submit" id="subscribe-submit" onClick="check()">
click me
</button>
function check()
{
if(!document.getElementById("subscribe-email").checkValidity())
{
//do stuff here ie. show errors
alert("input not valid!");
}else
{
callMeIfValid();
}
}
function callMeIfValid()
{
//submit form or whatever
alert("valid input");
}
check Validate email address in JavaScript? for validation and then implement it into an if statement in your omgemailgone method (if valid continue, else do nothing)
edit:
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\
".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA
-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
from the link
You can use Regular expressions to check that the email is valid on your omgemailgone() :
function omgemailgone (){
var mail = $('#subscribe-email').val();
//Example of regular expression
if(mail.match(/YourRegexp/)
{
//Do stuff
}
else alert("Invalid e-mail");
}
(using jQuery here)
u need a function that validate the email and return true or false
Validate email address in JavaScript?
<button type="submit" id="subscribe-submit" onClick="javascript:validateEmail(document.getElementById('subscribe-email').value) ? omgemailgone() : alert('email is wrong dude');" />
This is a quick solution, i recommend you to do it properly, not using inline onclick js

Categories

Resources