I have an input field of type text. Users should only be allowed to enter digits in the field. If they attempt to enter a non-digit, like a character, it should be ignored and not display in the field ( and not submitted to the server). I thought I could achieve this with the HTML5 pattern attribute:
<input class="form-control" data-remote="true" data-url="/contacts" data-method="put" pattern="^[0-9]*$" type="text" value="123456" name="contact[phone]" id="contact_phone">
But it doesn't work as expected. I can still enter any character into the field. There is no form submit button here. As soon as they tab out of field, the ajax call is made.
How can I achieve what I want with html5?
So you can totally do that by adding type="number" to your input field, It'll work in most browsers.
I'd recommend using sort of regex and a bit of JS to evaluate the input and then replace the input with permitted characters.
var phone_input = document.getElementById('contact_phone');
function validDigits(n){
return n.replace(/[^0-9]+/g, '');
}
phone_input.addEventListener('keyup', function(){
var field = phone_input.value;
phone_input.value = validDigits(field);
});
Here's a quick codepen
I'd also put a bit of validation on the model, just in case someone bypasses the JS.
I think it won't work with plain html5 since the pattern goes into affect after you submitted the form (It will make validation fail). But since you are already using js, you can just do it with for example the jQuery.keypress() function.
Related
I have a html input element on my page in which the user can enter his e-mail address:
<input type="email" id="yourEmail" name="yourEmail">
I do not send this field via the form directly but read it into a variable with javascript like this:
let email = document.getElementById('yourEmail').value.trim();
Now that works fine for normal e-mails, but as soon as I have special chars like German Umlauts, I get the transcribed email in the javascript variable. If I enter mail#gründlicher.de for example, the js variable contains the value mail#xn--grndlicher-beb.de. Since I want to show this data on a summary page back to the user before I sent it, that is really confusing to the user - it feels like something is broke (at least if you are not a techn nerd, understanding what happens).
Now I'm wondering: How do I get the text, that was actually entered by the user instead of the transcribed email? Obviously I could change form type="email" to type="text", but then I will also loose the e-mail specific keyboard on mobile devices, which I would like to have.
Try using type="text" to get the special characters to display, then use inputmode="email" to allow for e-mail-specific keyboard on mobile devices:
document.getElementById('yourEmail').addEventListener('change', function() {
console.log(this.value);
});
<input type="text" inputmode="email" id="yourEmail" name="yourEmail">
I have a client who wants me to punctuate all currency inputs with commas and dollar signs. This means that I have to use a text input instead of a number input, which means that I cannot take advantage of the inbuilt validation that number inputs have, chiefly min, max, step, and simply validating that what the user enters is in fact a numeric string. My idea is therefore to create a text input copy of the actual numeric input, hide the actual one, format the contents of the text input as the user types, and copy them over into the hidden numeric input so that they can be validated and submitted from there. What is the best way with javascript to display any validation errors that might pop up from the hidden number input? I am specifically looking at the constraint validation api:
https://developer.mozilla.org/en-US/docs/Web/API/Constraint_validation
Here's the example html:
<!-- hidden actual input field -->
<input id="real" name="cost" type="number" min="0" max="1000" step=".01" style="display:none;" />
<!-- visible, fake, punctuated input field -->
<input id="punctuated" type="text" />
So I am wanting to find a way to take any validation objects in the DOM for the first input and copy them over to the 2nd. I have tried this so far (see below), but it appears that the validity and validationMessage DOM properties are readonly:
var punctuated = document.getElementById('punctuated');
var real = document.getElementById('real');
punctuated.validationMessage = real.validationMessage;
punctuated.validity = real.validity;
First option: To add the same class to both inputs and use document.getElementsByClassName('some-class')
Second option: To use a single input and on (keyup) call the validation function which will check if the user input matches the regex you need
This appears to be the answer:
punctuated.setCustomValidity(real.validationMessage);
I just bound that to the page load, and a click and keyup event for the punctuated input, and it seems to work. So when the user types stuff into the punctuated input, it gets copied over to the real input and validated using the html attributes, and then the click and keyup events pass the validation message to the punctuated input.
I have to validate an input field, but I have problems when the user copy and paste something inside the input
This is my code
<input type="text" ng-change="calculate()" ng-pattern="coordsPattern" ng-model="from" class="input-coords" placeholder="(x|y)">
where the coordsPattern is:
$scope.coordsPattern = /^\(?\-?\d{1,3}\|\-?\d{1,3}\)?$/;
the input can take
(158|158)
-158|158
(-158|158
.....etc
but when the user copy and paste the same thing from a different page, depending on browser to browser, the input looks like (158|158) but the pattern is invalid because when copying there are hidden tabs or spaces between chars. for example
((tab)(tab)158(tab)|(tab)(tab)-158(tab)
but in the input text looks like (158|-158 so for the user is a valid input
the input is valid (because in the calculate() function I clean the input from spaces and tabs) but invalid with that pattern and angular doesn't execute the calculate() function.
this one is a copy&paste text which includes hidden tabs
(-91|-18)
Thank you
EDIT
this is the var_dump of the string
string '(â€-â€91‬‬|â€-â€18‬‬)' (length=33)
it contains special chars! neither tabs or spaces!
maybe I have to find a different solution to validate the input...
$scope.coordsPattern = /^\s*?\(?\s*?\-?\s*?\d{1,3}\s*?\|\s*?\-?\s*?\d{1,3}\s*?\)?\s*?$/;
This should match the expected input even when there are whitespace characters inserted.
I'm using MVC 3 with Razor and using unobtrusive client validation. Things are working great, but I want to be able to reset the form if a user decides he wants to start over or cancel his action. It seems that there is a lot of meta data attached to each form element when using the validation.
<input type="text" value="" name="User.FirstName" id="User_FirstName" data-val-required="The First Name field is required." data-val-length-max="50" data-val-length="The field FirstName must be a string with a maximum length of 50." data-val="true" class="text-box single-line">
The jQuery snippet here shows my problem. When you try to manually reset the value of the text field, some other javascript is intercepting execution after I clear the value and it sets it back to what it was:
$("#btnReset").click(function () {
alert($("#User_FirstName").val());
$("#User_FirstName").val("");
alert($("#User_FirstName").val());
});
I'm looking for pointers here on how to clear form values when a user clicks a button. It seems like such a simple task, but I can find no documentation how to accomplish this and I haven't found anything here or elsewhere to help.
I was using an html input of type reset rather than the button type. The reset should not have been used in this case.
I am working in Javascript. I am trying to make a function on the keypress event. I want to make function for validation on mobile number. I want to allow only digits in it. I also want to allow ctrl+v and ctrl+a in this but I dont want to allow V and A as characters.
I have seen many answers here but no one is purely same.
If you only care that digits are entered, as it seems from your question, this Jquery code will work.
It uses on keyup() and thus it will work on ctrl+v as well. It won't work if someone uses right-click to paste, and for that reason, you can just disable right clicking on that field.
It works by stripping off the last character of the input value if it is not a number. So if a user enters 25s or 25ss, it will get stripped down to 25.
Live Demo
The Jquery
$(document).ready(function(){
$('#number').keyup(function(){
var input = this.value;
while (isNaN(input))
{
input = input.substring(0,input.length-1);
$('#number').val(input);
}
});
//disable right click on the field
$('#number').bind("contextmenu",function(e){
return false;
});
});
You can use HTML5 input tags which use the pattern attribute.
<form>
<input name="name" value="" pattern="\d+" required/>
<input type="submit"/>
</form>