Preventing spaces in input on material ui (mui) - html

<FormControl variant="standard">
<InputLabel className="input-box-label" htmlFor="component-helper">My Value</InputLabel>
<Input
id="component-helper"
value={myValue}
onChange={handleChangeMyValue}
/>
</FormControl>
In this block of code, I'm wanting to make sure a user can't put any spaces as part of myValue. I can't really work out from the docs https://mui.com/material-ui/api/text-field/ how to put validation on form inputs (this includes adding other restraints such as only lower case letters, or any regex pattern for example).
Another aside thought, are forms redundant when one is dealing with 'state' as opposed to 'submitting' a form as would happen when not writing a single page app with a system like React? What is the benefit of actually having a <form> element in there if nothing is ever submitted?

Related

Correct 508 markup for requiring one of a set of checkboxes

I have a form that has a set of checkboxes. The user needs to check one or more of these. I'm confused as to how to deal with this via form validation and markup. I have an Error summary box that I can add a message, but my other form fields also have a message under each field that specifies the error, but since this is an issue with the set, I don't think that would be appropriate, so I assume just having it in the error summary box and being able to click on a link to the first of the set of checkboxes would be acceptable? Secondly, what about aria tagging? Would aria-required be appropriate? If so, how do you specify this for the entire set of checkboxes rather than each one individually, since none of these are required in and of themselves?
There isn't good markup to say a group of stuff is required but each one individually isn't necessarily required (although at least one is required). It's hard enough to express that in English :-)
With aria, you can sort of get around that.
<div role="group" aria-label="my list of checkboxes, you must select at least one">
<input type="checkbox"...>
...
<input type="checkbox"...>
</div>
aria-required="true" isn't allowed on the group.

HTML - Lock default value in text area and user insert more info

Im not sure on how to explain this but, what I want to know is there if there is any way to "lock" just one part of an text area in a html form. Example:
<input name="example" type="text" id="example" valeu="__this part cant be modified__, and here user insert aditional info" />
And then I get this field value as like: "this part cant be modified + what user typed"
Thank you
I don't think you can, your best bet would probably to just append your default value to their input upon submission.
No, there isn’t, not for input elements, not for textarea elements.
You can however create an impression of such behavior, e.g. having some text and an input element on the same line and setting their style as similar as possible (setting all text, background, and border properties). Of course, the form data would still consist of the input value. And prepending the fixed text to it in client-side JavaScript would be possible but normally pointless, since it would be inherently unreliable and since you can simply make the form handler behave as if it got that string (i.e., make it have it as built-in data).

does it matter where i put a hidden field in an html page?

To get additional ID information (like the page name) about the page when it's submitted.
Thanks
No, it shouldn't matter, as long as it is within the form.
It must be within the form. It doesn't matter where, unless you do something like this:
<form>
<input type="text" name="data[]" value="value1" />
<input type="hidden" name="data[]" value="value2" />
<input type="text" name="data[]" value="value3" />
</form>
In this case the data array isn't associative, so the position of the elements does matter.
Similarily, if you'd traverse your POST / GET data with a foreach loop without paying attention to the array keys, you could get problems (but if you have an associative array, you should use the associations, especially in user input).
I mention these things just to make the answer more complete. In most cases the simple answer applies - position of hidden fields does not matter.
No. Values from an HTML form are mostly treated as being an associative array. To that end, the order in which the elements appear are of hardly any concern.
It matters in the sense that the order of data fields in submitted form data normally corresponds to the order of fields in HTML markup. You can see this easily if you use the default method (GET), so that the fields will appear in the URL.
There is no requirement on this; it is just how browsers tend to behave. Any robust form data processing does not count on any particular order.
I have sometimes observed browser rendering oddities that seemed to depend on the placement of hidden fields. It sounds weird, because hidden fields should not affect rendering.

HTML input - name vs. id [duplicate]

This question already has answers here:
Difference between id and name attributes in HTML
(22 answers)
Closed 3 years ago.
When using the HTML <input> tag, what is the difference between the use of the name and id attributes especially that I found that they are sometimes named the same?
In HTML4.01:
Name Attribute
Valid only on <a>, <form>, <iframe>, <img>, <map>, <input>, <select>, <textarea>
Name does not have to be unique, and can be used to group elements together such as radio buttons & checkboxes
Can not be referenced in URL, although as JavaScript and PHP can see the URL there are workarounds
Is referenced in JavaScript with getElementsByName()
Shares the same namespace as the id attribute
Must begin with a letter
According to specifications is case sensitive, but most modern browsers don't seem to follow this
Used on form elements to submit information. Only input tags with a name attribute are submitted to the server
Id Attribute
Valid on any element except <base>, <html>, <head>, <meta>, <param>, <script>, <style>, <title>
Each Id should be unique in the page as rendered in the browser, which may or may not be all in the same file
Can be used as anchor reference in URL
Is referenced in CSS or URL with # sign
Is referenced in JavaScript with getElementById(), and jQuery by $(#<id>)
Shares same name space as name attribute
Must contain at least one character
Must begin with a letter
Must not contain anything other than letters, numbers, underscores (_), dashes (-), colons (:), or periods (.)
Is case insensitive
In (X)HTML5, everything is the same, except:
Name Attribute
Not valid on <form> any more
XHTML says it must be all lowercase, but most browsers don't follow that
Id Attribute
Valid on any element
XHTML says it must be all lowercase, but most browsers don't follow that
This question was written when HTML4.01 was the norm, and many browsers and features were different from today.
The name attribute is used for posting to e.g. a web server. The id is primarily used for CSS (and JavaScript). Suppose you have this setup:
<input id="message_id" name="message_name" type="text" />
In order to get the value with PHP when posting your form, it will use the name attribute, like this:
$_POST["message_name"];
The id is used for styling, as said before, for when you want to use specific CSS content.
#message_id
{
background-color: #cccccc;
}
Of course, you can use the same denomination for your id and name attribute. These two will not interfere with each other.
Also, name can be used for more items, like when you are using radio buttons. Name is then used to group your radio buttons, so you can only select one of those options.
<input id="button_1" type="radio" name="option" />
<input id="button_2" type="radio" name="option" />
And in this very specific case, I can further say how id is used, because you will probably want a label with your radio button. Label has a for attribute, which uses the id of your input to link this label to your input (when you click the label, the button is checked). An example can be found below
<input id="button_1" type="radio" name="option" /><label for="button_1">Text for button 1</label>
<input id="button_2" type="radio" name="option" /><label for="button_2">Text for button 2</label>
IDs must be unique
...within page DOM element tree so each control is individually accessible by its id on the client side (within browser page) by
JavaScript scripts loaded in the page
CSS styles defined on the page
Having non-unique IDs on your page will still render your page, but it certainly won't be valid. Browsers are quite forgiving when parsing invalid HTML. but don't do that just because it seems that it works.
Names are quite often unique but can be shared
...within page DOM between several controls of the same type (think of radio buttons) so when data gets POSTed to server only a particular value gets sent. So when you have several radio buttons on your page, only the selected one's value gets posted back to server even though there are several related radio button controls with the same name.
Addendum to sending data to server: When data gets sent to server (usually by means of HTTP POST request) all data gets sent as name-value pairs where name is the name of the input HTML control and value is its value as entered/selected by the user. This is always true for non-Ajax requests. In Ajax requests name-value pairs can be independent of HTML input controls on the page, because developers can send whatever they want to the server. Quite often values are also read from input controls, but I'm just trying to say that this is not necessarily the case.
When names can be duplicated
It may sometimes be beneficial that names are shared between controls of any form input type. But when? You didn't state what your server platform may be, but if you used something like ASP.NET MVC you get the benefit of automatic data validation (client and server) and also binding sent data to strong types. That means that those names have to match type property names.
Now suppose you have this scenario:
you have a view with a list of items of the same type
user usually works with one item at a time, so they will only enter data with one item alone and send it to server
So your view's model (since it displays a list) is of type IEnumerable<SomeType>, but your server side only accepts one single item of type SomeType.
How about name sharing then?
Each item is wrapped within its own FORM element and input elements within it have the same names so when data gets to the server (from any element) it gets correctly bound to the string type expected by the controller action.
This particular scenario can be seen on my Creative stories mini-site. You won't understand the language, but you can check out those multiple forms and shared names. Never mind that IDs are also duplicated (which is a rule violation) but that could be solved. It just doesn't matter in this case.
name identifies form fields*; so they can be shared by controls that stand to represent multiple possibles values for such a field (radio buttons, checkboxes). They will be submitted as keys for form values.
id identifies DOM elements; so they can be targeted by CSS or JavaScript.
* name's are also used to identify local anchors, but this is deprecated and 'id' is a preferred way to do so nowadays.
name is the name that is used when the value is passed (in the URL or in the posted data). id is used to uniquely identify the element for CSS styling and JavaScript.
The id can be used as an anchor too. In the old days, <a name was used for that, but you should use the id for anchors too. name is only to post form data.
name is used for form submission in the DOM (Document Object Model).
ID is used for a unique name of HTML controls in the DOM, especially for JavaScript and CSS.
The name defines what the name of the attribute will be as soon as the form is submitted. So if you want to read this attribute later you will find it under the "name" in the POST or GET request.
Whereas the id is used to address a field or element in JavaScript or CSS.
The id is used to uniquely identify an element in JavaScript or CSS.
The name is used in form submission. When you submit a form only the fields with a name will be submitted.
The name attribute on an input is used by its parent HTML <form>s to include that element as a member of the HTTP form in a POST request or the query string in a GET request.
The id should be unique as it should be used by JavaScript to select the element in the DOM for manipulation and used in CSS selectors.
I hope you can find the following brief example helpful:
<!DOCTYPE html>
<html>
<head>
<script>
function checkGender(){
if(document.getElementById('male').checked) {
alert("Selected gender: "+document.getElementById('male').value)
}else if(document.getElementById('female').checked) {
alert("Selected gender: "+document.getElementById('female').value)
}
else{
alert("Please choose your gender")
}
}
</script>
</head>
<body>
<h1>Select your gender:</h1>
<form>
<input type="radio" id="male" name="gender" value="male">Male<br>
<input type="radio" id="female" name="gender" value="female">Female<br>
<button onclick="checkGender()">Check gender</button>
</form>
</body>
</html>
In the code, note that both 'name' attributes are the same to define optionality between 'male' or 'female', but the 'id's are not equals to differentiate them.
Adding some actual references to W3C documentation that authoritatively explain the role of the 'name' attribute on form elements. (For what it's worth, I arrived here while exploring exactly how Stripe.js works to implement safe interaction with the payment gateway Stripe. In particular, what causes a form input element to get submitted back to the server, or prevents it from being submitted?)
The following W3C documentation is relevant:
HTML 4: https://www.w3.org/TR/html401/interact/forms.html#control-name Section 17.2 Controls
HTML 5: https://www.w3.org/TR/html5/forms.html#form-submission-0 and
https://www.w3.org/TR/html5/forms.html#constructing-the-form-data-set Section 4.10.22.4 Constructing the form data set.
As explained therein, an input element will be submitted by the browser if and only if it has a valid 'name' attribute.
As others have noted, the 'id' attribute uniquely identifies DOM elements, but is not involved in normal form submission. (Though 'id' or other attributes can of course be used by JavaScript to obtain form values, which JavaScript could then use for Ajax submissions and so on.)
One oddity regarding previous answers/commenters concern about id's values and name's values being in the same namespace. So far as I can tell from the specifications, this applied to some deprecated uses of the name attribute (not on form elements). For example https://www.w3.org/TR/html5/obsolete.html:
"Authors should not specify the name attribute on a elements. If the attribute is present, its value must not be the empty string and must neither be equal to the value of any of the IDs in the element's home subtree other than the element's own ID, if any, nor be equal to the value of any of the other name attributes on a elements in the element's home subtree. If this attribute is present and the element has an ID, then the attribute's value must be equal to the element's ID. In earlier versions of the language, this attribute was intended as a way to specify possible targets for fragment identifiers in URLs. The id attribute should be used instead."
Clearly, in this special case, there's some overlap between id and name values for 'a' tags. But this seems to be a peculiarity of processing for fragment ids, not due to general sharing of namespace of ids and names.
An interesting case of using the same name: input elements of type checkbox like this:
<input id="fruit-1" type="checkbox" value="apple" name="myfruit[]">
<input id="fruit-2" type="checkbox" value="orange" name="myfruit[]">
At least if the response is processed by PHP, if you check both boxes, your POST data will show:
$myfruit[0] == 'apple' && $myfruit[1] == 'orange'
I don't know if that sort of array construction would happen with other server-side languages, or if the value of the name attribute is only treated as a string of characters, and it's a fluke of PHP syntax that a 0-based array gets built based on the order of the data in the POST response, which is just:
myfruit[] apple
myfruit[] orange
Can't do that kind of trick with ids. A couple of answers in What are valid values for the id attribute in HTML? appear to quote the spec for HTML 4 (though they don't give a citation):
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be
followed by any number of letters, digits ([0-9]), hyphens ("-"),
underscores ("_"), colons (":"), and periods (".").
So the characters [ and ] are not valid in either ids or names in HTML4 (they would be okay in HTML5). But as with so many things html, just because it's not valid doesn't mean it won't work or isn't extremely useful.
If you are using JavaScript/CSS, you must use the 'id' of a control to apply any CSS/JavaScript stuff on it.
If you use name, CSS won't work for that control. As an example, if you use a JavaScript calendar attached to a textbox, you must use the id of the text control to assign it the JavaScript calendar.

Can a user language change form values in html?

My application has a form with 2 submit buttons:
<input name="rating" class="Show" type="submit" value="Show answer">
<input name="rating" class="Skip" type="submit" value="Skip">
However I noticed some errors in GAE logs:
ValueError: invalid literal for int() with base 10: 'Voir la r\xe9ponse'
ValueError: invalid literal for int() with base 10: 'Sauter'
Basically it's the value of the form buttons, in French, whereas my app is in English.
How can a user change the form submit values? For example with google translate etc?
How can I handle this?
Yeah, that'll be Google Translate. It translates the text on the buttons as well. If you really want to prevent this, you'll have to make sure Google can't translate the text on the button. Note: these answers are not semantic HTML. Not sure if there's a cleaner method, I hope so, but this is what first springs to mind:
Method 1: hidden inputs
Since you're using buttons anyway, you might as well have them submit something. Put each button in its own form, add a hidden field, and use the value of the hidden field to determine what page to load next.
Downside: a lot of extra html, not really maintenance-friendly
Method 2: numeric value
Change the value of the buttons into something numeric, like 0 and 1. Hide the button's value with CSS and give the button a background image that shows the text. Load the page based on the numeric value.
Downside: very bad accessibility (screen readers, etc.), text on button won't be translated.
I really do hope there's better alternatives I haven't thought of yet.