Prevent unallowed pasting into text-input - javascript

I'm trying to prevent the user from pasting unallowed text into an input field. The Input is a randomly generated 8 digit Code, that contains letters and numbers.
But I don't want the user to paste any text that contains other characters.
my input field:
<input type='text' id='form-code-field' name='code' maxlength='8'>
Note:
I'm not looking for something like the readonly attribute, because the user still has to input alphanumeric text into the field.

You could test value input using a regex on input event:
$('#form-code-field').on('input', function(){
if(!/^[a-z0-9]+$/i.test(this.value)) this.value = $(this).data('oldValue') || "";
else $(this).data('oldValue', this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type='text' id='form-code-field' name='code' maxlength='8'>

For HTML5 browsers you can also do this, and no script required:
<input type='text' name='code' maxlength='8' pattern="^[a-z0-9]+$" title="a-z0-9">
This will not stop someone from write non valid characters, the pattern will be evaluated on submit and will abort the submit with a message if not matched.
Update
I added a plain javascript version for those who don't use jQuery, which works globally on a form. Just set the "pattern" on a input field and it kicks in.
The script also works on input on non HTML5 browsers.
A "safety" note:
As a client side evaluation, this by no means is 100% safe to just store server side, you always need to check whats posted before doing anything with it.
document.getElementById('form').addEventListener('input', function(e){
if (e.target.pattern && e.target.pattern.length > 0) {
var regex = new RegExp(e.target.pattern,"i");
if(!regex.test(e.target.value)) {
if (e.target.value.length > 0) {
e.target.value = e.target.getAttribute('data-old-value') || "";
} else {
e.target.setAttribute('data-old-value', "");
}
} else {
e.target.setAttribute('data-old-value', e.target.value);
}
}
}, false);
<form id="form">
Only alphanum (max 8): <input type='text' id='form-code-field' name='code' maxlength='8' pattern="^[a-z0-9]+$" title="a-z0-9"><br /><br />
Any character (max 5): <input type='text' id='form-code-field' name='code' maxlength='5' ><br />
</form>

Related

How To Validate Form Field Using Javascript

I am trying to validate my form phone field to prevent users from entering the same numbers in my javascript.
If the number provided by the user matches with the same numbers in my javascript, They will get a warning and the form would not submit.
However, I noticed that my code below shows the warning whether the numbers match or not.
I need corrections to know what I am doing wrong. Thanks.
Code below;
$('.validate').hide();
$('body').on('blur', '#phone', function() {
$('.validate').hide();
isphone($(this).val());
});
function isphone(phone) {
if (phone === "1234" || phone === "23456"){
$(".validate").show();
} else {
$(".validate").hide();
}
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<form action='' method='POST' id="submitForm" >
<input type="phone" name='phone' required='' id="phone" placeholder="0000-000-0000"/>
<div class="validate"><span style="color: red;"><b>Please enter a valid phone!</b></span></div>
<button href='/' type='submit' id="submitForm">Process</button>
</form>
I believe this should work.
I move the changes for hiding and showing $('.validate') to the isphone function, and removed that done variable that wasn't doing anything useful (used if...else instead).
Also, don't use document.getElementById if you're already using JQuery.
$('.validate').hide();
$('body').on('blur', '#phone', function() {
$('.validate').hide();
isphone($(this).val());
});
function isphone(phone) {
if (phone === "1234" || phone === "23456"){
$(".validate").hide();
} else {
$(".validate").show();
}
}

no ability to enter numbers or special chars in input

The below works for the most part; however numbers can still be entered via two ways: 'copy paste' and also from browser cache/suggestions, i.e. if your browser is giving you suggestions from your history to fill the input. Numbers can still be achieved in those two ways.
Anyway to eliminate the ability for numbers being entered in the field completely?
<input type="text" data-value-field="value" name="styleName" onkeypress="return /[a-z]/i.test(event.key)" />
Check this
abc.oninput = function() {
const val = this
if (/[0-9~`!##$%\^&*()+=\-\[\]\\';,/{}|\\":<>\?£.]+/.test(this.value)) {
const i = this.value.match(/[0-9~`!##$%\^&*()+=\-\[\]\\';,/{}|\\":<>\?£.]+/g)
if (i !== null) {
i.map(function(el) {
val.value = val.value.replace(el, '')
})
}
}
}
<input type="text" data-value-field="value" name="styleName" id="abc" />
onpaste="return false" is used to cancel the paste event.
autocomplete="off" is used to prevent auto-completion.
setInterval(() => { ... }, 100); is used to regularly check the input and remove any numbers or special characters. This prevents the user from being able to use input.value = " ... " in the Developer console to set the input's value to something invalid, as the input will automatically be corrected.
const input = document.getElementById('cleanse');
setInterval(() => {
input.value = input.value.replace(/[^a-zA-Z ]/g, "");
}, 100);
<input type="text" data-value-field="value" name="styleName" onkeypress="return /[a-z]/i.test(event.key)" onpaste="return false" autocomplete="off" id="cleanse" />

jQuery Click Function, input value length and pattern

I have a problem, that I'm struggling with since 2 days.
I have a webpage that asks for the phone number, and I'm trying to make a "validator" for the phone number into the input tab, but it seems that I cannot figure out how to check the minlength for the input tab, neither how to accept only numerical characters. Here's the code:
$("#start").click(function(){ // click func
if ($.trim($('#phonenr').val()) == ''){
$("#error").show();
I tried adding:
if ($.trim($('#phonenr').val()) == '') && ($.trim($('#phonenr').val().length) < 15)
But it just won't work.
Any help would be appreciated. Also please tell me how can I make it allow only numbers?
Thank you!
Final code, with help of #Saumya Rastogi.
$("#start").click(function(){
var reg = /^\d+$/;
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$("#error").show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$("#error").show();
} else {
You can make your validation work.
You can use test (Regex Match Test) for accepting only digits in the input text. Just use javascript's substring to chop off the entered non-digit character like this:
$(function() {
$('#btn').on('click',function(e) {
var reg = /^\d+$/; // <------ regex for validatin the input should only be digits
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$('label.error').show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$('label.error').show();
} else {
$('label.error').hide();
}
});
})
label.error {
display: none;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="phonenr" type="text" value=""><br>
<label class='error'>Invalid Number</label>
<br><br>
<button id="btn">Click to Validate</button>
Hope this helps!
If you are using HTML5, then you can make use of the new number input type available
<input type="number" name="phone" min="10" max="10">
You can also use the pattern attribute to restrict the input to a specific Regular expression.
If you are looking for the simplest way to check input against a pattern and display a message based on validity, then using regular expressions is what you want:
// Wait until the DOM has been fully parsed
window.addEventListener("DOMContentLoaded", function(){
// Get DOM references:
var theForm = document.querySelector("#frmTest");
var thePhone = document.querySelector("#txtPhone");
var btnSubmit = document.querySelector("#btnSubmit");
// Hook into desired events. Here, we'll validate as text is inputted
// into the text field, when the submit button is clicked and when the
// form is submitted
theForm.addEventListener("submit", validate);
btnSubmit.addEventListener("click", validate);
thePhone.addEventListener("input", validate);
// The simple validation function
function validate(evt){
var errorMessage = "Not a valid phone number!";
// Just check the input against a regular expression
// This one expects 10 digits in a row.
// If the pattern is matched the form is allowed to submit,
// if not, the error message appears and the form doesn't submit.
!thePhone.value.match(/\d{3}\d{3}\d{4}/) ?
thePhone.nextElementSibling.textContent = errorMessage : thePhone.nextElementSibling.textContent = "";
evt.preventDefault();
}
});
span {
background: #ff0;
}
<form id="frmTest" action="#" method="post">
<input id="txtPhone" name="txtPhone"><span></span>
<br>
<input type="submit" id="btnSubmit">
</form>
Or, you can take more control of the process and use the pattern HTML5 attribute with a regular expression to validate the entry. Length and digits are checked simultaneously.
Then you can implement your own custom error message via the HTML5 Validation API with the setCustomValidity() method.
<form id="frmTest" action="#" method="post">
<input type="tel" id="txtPhone" name="txtPhone" maxlength="20"
placeholder="555-555-5555" title="555-555-5555"
pattern="\d{3}-\d{3}-\d{4}" required>
<input type="submit" id="btnSubmit">
</form>
Stack Overflow's code snippet environment doesn't play well with forms, but a working Fiddle can be seen here.

Javascript disable input field

I have two input fields one is for a phone number another is for an email. I would like to disable one field based on the user selection. Should a user click and enter input in either field, it would disable the other and vice versa.
I have written code but it seems to only disable the email field upon entering in numbers in the phone field. Removing the numbers in the phone field removes the disabled from the email input field.
IN MY HTML
<input type="number" name="number" placeholder="hone" class="cellphone" data-cp-visibility="new-user" id="phone">
<input type="email" name="email" placeholder="enter email" class="email" data-cp-visibility="new-user" id="email">
IN JAVASCRIPT
$('#phone').live('blur',function(){
if(document.getElementById('phone').value > 1) {
$('#email').attr('disabled', true);
} else {
$('#email').attr('disabled', false);
}
});
$('#email').live('blur',function(){
if(document.getElementById('email').value > 1) {
$('#phone').attr('disabled', true);
} else {
$('#phone').attr('disabled', false);
}
});
Ultimately I what I am trying to accomplish is that a user can click in either field and then enter input, upon doing so, the other field is disabled. Should they choose to remove the text they entered, it would remove the disabled feature and then they could choose the opposite input field.
I am not sure why it only works for one field and not the other or why if you enter in 333-333-3333 in the phone field it breaks the disabled, but 33333333 works fine.
Any ideas or insight as to what I may be missing?
to fix the dash issue you are having with the phone input, you can try changing it to:
<input type="text" required="" pattern="\d{3}[\-]\d{3}[\-]\d{4}" name="phone" id="phone" data-cp-visibility="new-user" placeholder="123-345-5678">
and here is another version of the js:
var $phone = $('#phone'),
$email = $('#email');
$phone.on('keyup change', function() {
$email.prop('disabled', $(this).val() ? true : false );
});
$email.on('keyup change', function() {
$phone.prop('disabled', $(this).val() ? true : false );
});
You may use jQuery on instead of live. live is deprecated as of jQuery 1.7.
You can also look for the keyup/keydown event on the input element.
$(function(){
$('#phone').on('keyup',function(){
if($(this).val()!=="")
{
$('#email').prop('disabled', true);
}
else {
$('#email').attr('disabled', false);
}
});
$('#email').on('keyup',function(){
if($(this).val()!=="")
{
$('#phone').prop('disabled', true);
}
else {
$('#phone').prop('disabled', false);
}
});
});
Here is a working sample.
I would recommend using .on('input', ...) to listen for changes, this makes it so even if you use the increment/decrement buttons (or other forms of input) you'll trigger the event-handler. Then use .attr('disabled', boolean) to control enable/disabled state, see example below:
$(function() {
$('#phone').on('input', function() {
$('#email').attr('disabled', $(this).val() !== "");
});
$('#email').on('input', function() {
$('#phone').attr('disabled', $(this).val() !== "");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" placeholder="phone" id="phone">
<input type="email" placeholder="enter email" id="email">

i want to use onblur to validate alpha and hyphen for textbox in form

I want to use javascript to validate using onblur if the user is inputting only alpha values and hyphen in the textbox.
*First Name: <input type="text" name="fn" onblur="alphahyphen()"/> <br />
*Family Name: <input type="text" name="sn" onblur="alphahyphen()"/><br />
function alphahyphen(){
var letters = /^[a-z A-Z\-]+$/;
if(task3.fn.value.match(letters)){
return;
}else{
alert("Enter alpha");
}
}
I dont want it to show an error message when the field is left empty as i am using an onsubmit for that.
Any help?

Categories