HTML pattern matching not working - html

I have an <input> element with pattern validation.
<input type="text" id="some" pattern="^[A-Z]{5}$" name="some" maxlength="5" style="text-transform:uppercase" required/>
The pattern matching works if a user inputs all uppercase characters but fails if any is lowercase. Why is pattern matching not considering style="text-transform:uppercase"?

The text-transform is only a visual change, not a data change.
See the following example to debug the <input>:
function debug()
{
let inpItem = document.getElementById('some');
let inpValue = document.getElementById('some').value;
//alert the actual value on input.
console.log(inpValue);
//set text-transform to default.
inpItem.style='text-transform:none';
}
input {
text-transform:uppercase;
}
<button onclick="debug()">Debug</button>
<input type="text" id="some" pattern="^[A-Z]{5}$" name="some" maxlength="5" required/>
How you can only input in uppercase?
You can use JavaScript to set all input values to the uppercase value.
function debug()
{
let inpItem = document.getElementById('some');
let inpValue = document.getElementById('some').value;
//alert the actual value on input.
console.log(inpValue);
//set text-transform to default.
inpItem.style='text-transform:none';
}
<button onclick="debug()">Debug</button>
<input type="text" id="some" pattern="^[A-Z]{5}$" name="some" maxlength="5" onkeyup="javascript:this.value=this.value.toUpperCase();" required/>

Pattern ignores text-decoration: uppercase; because it's only styling and original text is still formatted in the way it was inputted.
You should change your pattern to check both uppercase and lowercase symbols.
^[A-Za-z]{5}$

I don't know exactly why this is happenning, maybe the pattern is processed before the style is given to the input text, but I see you are trying to create a pattern to accept up to five latin characters(uppercase or lowercase, since you are changing them all to uppercase), so why don't you just add lowercase letters to your pattern?
pattern="^[A-Za-z]{5}$"

Your regex will work only if there are 5 consecutive uppercase letters, you can check it here http://regexr.com

Related

phone number validation with different first letters

I'm trying to validate hungarian phone numbers which are a little bit harder than other nubmers because we accept 2 types of them:
examples:
+36201234567
+36301234567
+36701234567
but these ones are also valid:
06201234567
06301234567
06701234567
I checked the overflow questions already but couldn't find any solution for the first letter if I can accept '+' and '0' aswell.
This is my code which only accepts the '+' format atm.
<input type="tel" pattern='[\+](36)(20|30|70)\d{7}' class="form-control" id="phone" name="phone" placeholder="+36301234567" required="required">
You can make another comination using | like this:
pattern="([\+](36)(20|30|70)\d{7})|((06)\d{9})"
And also as #grumpy said the best practice is to remove all chars that are not numbers
You can also add a JS function like this with onkeypress events like this onkeypress="return Validate(event)"
`function Validate(event) {
var regex = new RegExp("^[0-9+]");
var key = String.fromCharCode(event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
}`
Check this regex: ((?:\+?3|0)6)(?:-|\()?(\d{1,2})(?:-|\))?(\d{3})-?(\d{3,4}). It accepts all kinds of Hungarian phone numbers.
<input type="tel" pattern='((?:\+?3|0)6)(?:-|\()?(\d{1,2})(?:-|\))?(\d{3})-?(\d{3,4})' class="form-control" id="phone" name="phone" placeholder="+36301234567" required="required">

Input type=number Safari still allows letters with stepper

I have an input field which only allows number:
<input class="border" type="number" numeric step="0.1" inputmode="numeric" digitOnly maxlength="6" formControlName="resultInput" pattern="[0-9]+"/>
I set more parameters than needed just to check if it would work with these. Unluckily it didn't.
When I am using it on Chrome it works, but when I am using it on Safari it doesn't.
Unfortunately, many browsers will only validate the input for an input with type="number" upon form submission. In such a case, the following prompt will appear (example from Safari):
I've modified your snippet to remove any non-numeric input as it is entered. I have tested that this snippet works on the Chrome, Firefox and Safari.
<input class="border" type="number" numeric step="0.1" inputmode="numeric" digitOnly maxlength="6" formControlName="resultInput" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1').replace(/^0[^.]/, '0');" />
If you were willing to forgo the stepper, you could avoid having a single non-numerical character remove the entire input:
<input class="border" type="text" inputmode="numeric" digitOnly maxlength="6" formControlName="resultInput" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1').replace(/^0[^.]/, '0');" />
In these snippets, we use:
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1').replace(/^0[^.]/, '0');"
to remove all characters that would result in the value in the input not matching a typical numeric form (no leading zeroes, no more than one decimal point).
Be warned: while you can use HTML, CSS and JavaScript to restrict what users enter when using your website normally (known as 'client-side validation'), it is trivial to bypass the restrictions set this way.
If you are sending this data to a server for transformation, you should not trust that this data will only be numeric and of the form you expect. You should consider this type of validation to be purely for convenience's sake rather than providing any guarantee that the server will receive valid data.
The above series of "replace" did not work for me. Since my project is in Angular, I instead created a custom form field validator. That way, an error is presented to the user on invalid input (which prevents form submission):
public static numberInputValidator(min: number, max: number): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (isUndefinedOrEmpty(control?.value) || control.value <= min) {
return { numberRequired: true };
} else if(control.value > max) {
return { numberTooBig: true };
}
return null;
};
}
The only related attributes on the HTML input field are: type="number" step=".01"
To use it, add the validator to your FormControl in your FormGroup:
myControlName: new FormControl<undefined | number>(undefined, numberInputValidator(0, 100))
And even though the validator takes only number inputs, it will return numberRequired if the form field contains non-numeric characters.
You can then display custom error messages as such this (right after the <input> field) if using Angular Material form fields:
<mat-error *ngIf="vm.formGroup.get('myControlName')?.errors?.numberRequired">
<p>Amount must be greater than zero</p>
</mat-error>
<mat-error *ngIf="vm.formGroup.get('myControlName')?.errors?.numberTooBig">
<p>Amount must be less than or equal to 100</p>
</mat-error>

To allow only one numeric value in text box based on regular expression in AngularJs

I'm using ng-pattern :
<input type="text" ng-model="price" name="price_field" ng-pattern-restrict="/^[4]*$/" required only-digits>
Please let me know what to do that it does not accept any other numbers except 4. I am using directive for digits that is only-digits.
EDIT: SORRY WRONG ANGULAR VERSION - but if you can transform this to angularjs it will be work!
You can use (input) event in you HTML input element
<input type="number" (input)="check($event)">
Than in your ts you cehck value of input
check(event) {
console.log(event);
if (+event.data !== 4) {
event.target.value = '';
}
}
The pattern which you are mentioned is not a valid regex pattern. Instead of that try to use this /^([4]){1}?$/ Hope you will get it.
<input type="text" ng-model="price" name="price_field" ng-pattern-restrict="/^([4]){1}?$/" required only-digits>
Try to use below restrict pattern :
<input type="text" ng-model="price" name="price_field" ng-pattern-restrict="^[4]{1}?$" required only-digits>
And below validation message :
<div ng-messages="myForm.price_field.$error">
<span ng-message="pattern">Not a valid number!</span>
</div>

Is it possible to configure a required field to ignore white space?

The required attribute in HTML5 is very handy:
<input type="text" required>
But it still allows users to enter white space only.
Is there an HTML-only solution to this?
Use the pattern attribute combined with the required attribute. And be sure to include a title attribute as well, since most browsers insert the title text into the validation pop-up bubble.
<input required pattern=".*\S+.*" title="This field is required">
The .*\S+.* pattern requires at least one non-whitespace character, but also allows whitespace characters (spaces, tabs, carriage returns, etc.) at the beginning or end. If you don't want the user to be able to put whitespace at the beginning/end, then use this instead:
<input required pattern="\S(.*\S)?" title="This field is required">
Try the pattern attribute. You'll need a regex which specifies 'at least one character'.
You probably want this:
<input type="text" required pattern="\S(.*\S)?">
(At least one non-whitespace character and no whitespace at the beginning or end of the input)
Or if whitespace at the beginning and end are fine, then this:
<input type="text" required pattern=".*\S.*">
step 1
create a Javascript function:
function ignoreSpaces(event) {
var character = event ? event.which : window.event.keyCode;
if (character == 32) return false;
}
Step 2
use it on any text-input field in HTML.
<input type="text" id="userInput" onkeypress="return ignoreSpaces(event)">
Working example :
index.html
<html>
<body>
<input type="text" onkeypress="return ignoreSpaces(event)">
<script>
function ignoreSpaces(event) {
var character = event ? event.which : window.event.keyCode;
if (character == 32) return false;
}
</script>
</body>
</html>

How do you automatically set text box to Uppercase?

I am using the following style attribute to set the user input to uppercase so that when the user starts typing in the text box for example railway, then it should be altered to capital letters like RAILWAY without the user having to press the Caps-lock button.
This is the code I am using for the input:
<input type = "text" class = "normal" name = "Name" size = "20" maxlength = "20"> <img src="../images/tickmark.gif" border="0" style='text-transform:uppercase'/>
But I am not getting the desired output by using this attribute.
You've put the style attribute on the <img> tag, instead of the <input>.
It is also not a good idea to have the spaces between the attribute name and the value...
<input type="text" class="normal"
name="Name" size="20" maxlength="20"
style="text-transform:uppercase" />
<img src="../images/tickmark.gif" border="0" />
Please note this transformation is purely visual, and does not change the text that is sent in POST.
NOTE: If you want to set the actual input value to uppercase and ensure that the text submitted by the form is in uppercase, you can use the following code:
<input oninput="this.value = this.value.toUpperCase()" />
I think the most robust solution that will insure that it is posted in uppercase is to use the oninput method inline like:
<input oninput="this.value = this.value.toUpperCase()" />
EDIT
Some people have been complaining that the cursor jumps to the end when editing the value, so this slightly expanded version should resolve that
<input oninput="let p=this.selectionStart;this.value=this.value.toUpperCase();this.setSelectionRange(p, p);" />
The answers with the text-transformation:uppercase styling will not send uppercased data to the server on submit - what you might expect. You can do something like this instead:
For your input HTML use onkeydown:
<input name="yourInput" onkeydown="upperCaseF(this)"/>
In your JavaScript:
function upperCaseF(a){
setTimeout(function(){
a.value = a.value.toUpperCase();
}, 1);
}
With upperCaseF() function on every key press down, the value of the input is going to turn into its uppercase form.
I also added a 1ms delay so that the function code block triggers after the keydown event occured.
UPDATE
Per recommendation from Dinei, you can use oninput event instead of onkeydown and get rid of setTimeout.
For your input HTML use oninput:
<input name="yourInput" oninput="this.value = this.value.toUpperCase()"/>
The problem with the first answer is that the placeholder will be uppercase too. In case you want ONLY the input to be uppercase, use the following solution.
In order to select only non-empty input element, put required attribute on the element:
<input type="text" id="name-input" placeholder="Enter symbol" required="required" />
Now, in order to select it, use the :valid pseudo-element:
#name-input:valid { text-transform: uppercase; }
This way you will uppercase only entered characters.
try
<input type="text" class="normal"
style="text-transform:uppercase"
name="Name" size="20" maxlength="20">
<img src="../images/tickmark.gif" border="0"/>
Instead of image put style tag on input because you are writing on input not on image
Set following style to set all textbox to uppercase:
input { text-transform: uppercase; }
Using CSS text-transform: uppercase does not change the actual input but only changes its look.
If you send the input data to a server it is still going to lowercase or however you entered it. To actually transform the input value you need to add javascript code as below:
document.querySelector("input").addEventListener("input", function(event) {
event.target.value = event.target.value.toLocaleUpperCase()
})
<input>
Here I am using toLocaleUpperCase() to convert input value to uppercase.
It works fine until you need to edit what you had entered, e.g. if you had entered ABCXYZ and now you try to change it to ABCLMNXYZ, it will become ABCLXYZMN because after every input the cursor jumps to the end.
To overcome this jumping of the cursor, we have to make following changes in our function:
document.querySelector("input").addEventListener("input", function(event) {
var input = event.target;
var start = input.selectionStart;
var end = input.selectionEnd;
input.value = input.value.toLocaleUpperCase();
input.setSelectionRange(start, end);
})
<input>
Now everything works as expected, but if you have slow PC you may see text jumping from lowercase to uppercase as you type. If this annoys you, this is the time to use CSS, apply input: {text-transform: uppercase;} to CSS file and everything will be fine.
The issue with CSS Styling is that it's not changing the data, and if you don't want to have a JS function then try...
<input onkeyup="this.value = this.value.toUpperCase()" />
on it's own you'll see the field capitalise on keyup, so it might be desirable to combine this with the style='text-transform:uppercase' others have suggested.
Various answers here have various problems, for what I was trying to achieve:
Just using text-transform changes the appearance but not the data.
Using oninput or onkeydown changes the cursor position, so you can't, for instance, click in the middle of your existing input and edit it.
Saving the position works, but just seemed a bit kludgey.
It felt cleaner to me to just break the problem up into two parts: upper-casing what I'm typing while I type (text-transform), and upper-casing the submitted data (run toUpperCase onchange):
<input id = "thing" onchange="this.value = this.value.toUpperCase(); pr()" style=text-transform:uppercase /><p>
<b><span id="result"></span></b>
<script>function pr() {document.getElementById("result").innerHTML = document.getElementById("thing").value}</script>
Type something in that, hit return or click out of the input, then click in the middle of your previous entry, add some lc text, hit return...
IN HTML input tag just style it like follows
<input type="text" name="clientName" style="text-transform:uppercase" required>
in backed php/laravel use:
$name = strtoupper($clientName);
This will both show the input in uppercase and send the input data through post in uppercase.
HTML
<input type="text" id="someInput">
JavaScript
var someInput = document.querySelector('#someInput');
someInput.addEventListener('input', function () {
someInput.value = someInput.value.toUpperCase();
});
As nobody suggested it:
If you want to use the CSS solution with lowercase placeholders, you just have to style the placeholders separately. Split the 2 placeholder styles for IE compatibility.
input {
text-transform: uppercase;
}
input:-ms-input-placeholder {
text-transform: none;
}
input::placeholder {
text-transform: none;
}
The below input has lowercase characters, but all typed characters are CSS-uppercased :<br/>
<input type="text" placeholder="ex : ABC" />
<input style="text-transform:uppercase" type = "text" class = "normal" name = "Name" size = "20" maxlength = "20"> <img src="../images/tickmark.gif" border="0"/>
I went with the style text-transform:uppercase thing from poster. Then I just did the uppercase thing in php as well. Some people working too hard with that javascript.
You were close with the style being in the wrong place. You were trying to uppercase an image instead of the input.
$name = strtoupper($_POST['Name']);
I don't know why I wanted to throw in some extra stuff if it's a php page. This is something I like to do make it smoother for the person filling out the form.
<input style="text-transform:uppercase" type = "text" class = "normal" name = "Name" size = "20" maxlength = "20" value="<?php echo $name; ?>"> <img src="../images/tickmark.gif" border="0"/>
That's assuming you're using PHP as the backend and posting to the same page you are on. This will keep the user from having to fill out that part of the form again. Less annoying for the person filling out the form.
Try below solution, This will also take care when a user enters only blank space in the input field at the first index.
document.getElementById('capitalizeInput').addEventListener("keyup", () => {
var inputValue = document.getElementById('capitalizeInput')['value'];
if (inputValue[0] === ' ') {
inputValue = '';
} else if (inputValue) {
inputValue = inputValue[0].toUpperCase() + inputValue.slice(1);
}
document.getElementById('capitalizeInput')['value'] = inputValue;
});
<input type="text" id="capitalizeInput" autocomplete="off" />
Just use this oninput in your input field:
<div class="form-group col-2">
<label>PINCODE</label>
<input type="number" name="pincode" id="pincode" class="form-control" minlength="6" maxlength="6" placeholder="Enter Pincode" oninput="this.value = this.value.toUpperCase()" autocomplete="off">
</div>
Just add in your input(style="text-transform:uppercase")
<input type="text" class="normal" style="text-transform:uppercase" name="Name" size="20" maxlength="20">
<script type="text/javascript">
function upperCaseF(a){
setTimeout(function(){
a.value = a.value.toUpperCase();
}, 1);
}
</script>
<input type="text" required="" name="partno" class="form-control" placeholder="Enter a Part No*" onkeydown="upperCaseF(this)">