Input for entering and validating international telephone numbers. It adds a flag dropdown to any input, detects the user's country, displays a relevant placeholder and provides formatting/validation methods.
<script>
//<![CDATA[
var myGeoIpLookup = function (success, failure) {
$.get("https://ipinfo.io", function () {
}, "jsonp").always(function (resp) {
var countryCode = (resp && resp.country) ? resp.country : "";
success(countryCode);
});
}
//]]>
</script>
<h:form id="frmPhone">
<p:messages id="msgs">
<p:autoUpdate/>
</p:messages>
<div class="card">
<h5>Basic</h5>
<pe:inputPhone id="basic"
initialCountry="us"
value="#{inputPhoneView.phoneNumber}"
required="true"
requiredMessage="Basic is required!"
formatOnDisplay="true">
<p:ajax event="countrySelect" listener="#{inputPhoneView.onCountrySelect}" process="@none"/>
</pe:inputPhone>
<p:commandButton value="Submit" update="@form" actionListener="#{inputPhoneView.submit}" styleClass="ml-3"/>
<h5>Localized</h5>
<pe:inputPhone id="localized"
initialCountry="nl"
onlyCountries="nl,be,de"
localizedCountries="{'nl':'Nederland','be':'België','de':'Duitsland'}"
value="#{inputPhoneView.localized}"/>
<h5>GEO IP Lookup</h5>
<pe:inputPhone id="geoIp"
initialCountry="auto"
geoIpLookup="myGeoIpLookup"
value="#{inputPhoneView.geoIp}">
</pe:inputPhone>
<h5>Disabled</h5>
<pe:inputPhone disabled="true"/>
</div>
</h:form>
package org.primefaces.showcase.view.input;
import jakarta.annotation.PostConstruct;
import jakarta.faces.application.FacesMessage;
import jakarta.faces.context.FacesContext;
import jakarta.faces.view.ViewScoped;
import jakarta.inject.Named;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import io.quarkus.runtime.annotations.RegisterForReflection;
import lombok.Data;
import org.primefaces.event.SelectEvent;
import org.primefaces.extensions.model.inputphone.Country;
/**
* @author Jasper de Vries <jepsar@gmail.com>
*/
@Named
@ViewScoped
@Data
@RegisterForReflection(serialization = true)
public class InputPhoneView implements Serializable {
private static final long serialVersionUID = 1L;
private String phoneNumber;
private String localized;
private String geoIp;
private Map<String, String> localizedCountries;
@PostConstruct
protected void init() {
localizedCountries = new HashMap<>();
localizedCountries.put("nl", "Nederland");
localizedCountries.put("be", "België");
localizedCountries.put("de", "Duitsland");
}
public void onCountrySelect(final SelectEvent<Country> event) {
final Country country = event.getObject();
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_WARN, "Selected " + country.getName(), null));
}
public void submit() {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_INFO, "Phone Number " + phoneNumber, null));
}
}